<?php
/**
 * Created by PhpStorm.
 * User: user1
 * Date: 2018/9/3
 * Time: 14:26
 */

namespace app\common\model;

use think\Db;
use think\Exception;

class Admin extends BaseModel
{
    /**
     * 获取管理员列表
     * @param $where
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getAdminList($where) {

        $data = self::where($where)->paginate(input('param.limit'), false, ['query' => input('param.')]);

        return $data;
    }

    /**
     * 创建或者编辑管理员
     * @param $data
     * @param int $id
     * @return \think\response\Json
     */
    public static function createOrUpdateAdmin($data, $id = 0) {
        Db::startTrans();
        try {
            if ($id > 0) {
                $admin = self::get(['id' => $id]);
                if (!$admin) {
                    throw new Exception('管理员不存在');
                }
                $check_admin_login = self::where('username', '=', $data['username'])
                    ->where('id', 'neq', $id)
                    ->find();
                if ($check_admin_login) {
                    throw new Exception('登录账号已存在');
                }

                if ($data['password']) {
                    // 如果有修改密码
                    $data['password'] = md5($admin->salt . $data['password']);
                }

                $admin->allowField(true)->save($data); // 更新用户信息,只写入数据表有的字段（对象写法）

            } else {
                $check_admin_login = self::where('username', '=', $data['username'])->find();
                if ($check_admin_login) {
                    throw new Exception('用户名已存在');
                }
                if (!isset($data['password']) || !$data['password']) {
                    throw new Exception('添加账户必须输入密码');
                }
                $data['salt'] = getRandChar(6);
                $data['password'] = md5($data['salt'] . $data['password']);
                $data['create_id'] = session('org_login_account.id');
                self::create($data, true);// 创建用户信息,只写入数据表有的字段（静态写法）
            }
            Db::commit();
            return return_data('保存成功！');
        } catch (Exception $e) {
            Db::rollback();
            return return_data($e->getMessage(), 1);
        }
    }

    /**
     * 检查代理商账号是否已存在
     * @param $username
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function checkAgentAccount($username) {
        return self::where('username', '=', $username)->find();
    }
}